<?php
/**
 * FunAdmin
 * ============================================================================
 * 版权所有 2017-2028 FunAdmin，并保留所有权利。
 * 网站地址: http://www.FunAdmin.com
 * ----------------------------------------------------------------------------
 * 采用最新Thinkphp8实现
 * ============================================================================
 * Author: yuege
 * Date: 2019/9/21
 */

namespace app\common\controller;
use app\common\model\Menu;
use app\BaseController;
use think\App;
use think\facade\Filesystem;
use think\file\UploadedFile;
use think\Request;
use think\View;

class Backend extends BaseController
{
    protected $middleware = [

    ];

    /**
     * @var
     * 页面大小
     */
    protected $pageSize;
    /**
     * @var
     * 页数
     */
    protected $page;

    protected $view;
    /**
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->view = new View($this->app);
        // 控制器初始化
        $this->initialize();
        $this->assignCommon();
        if (empty(session('admin'))) {
            $this->redirect(__u('admin/login/index'));
        }
    }

    /**
     * 建立Token
     */
    protected function token()
    {
        return $this->request->buildToken();
    }

    public function assignCommon()
    {
        $menus = app(Menu::class)->toTree();
        $admin = session('admin');
        $this->view->assign(compact('menus', 'admin'));
    }


    /**
     * 加载模板输出
     * @access protected
     * @param  string $template 模板文件名
     * @param  array  $vars     模板输出变量
     * @param  array  $config   模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $config = [])
    {
        return $this->view->fetch($template, $vars, $config);
    }

    /**
     * 渲染内容输出
     * @access protected
     * @param  string $content 模板内容
     * @param  array  $vars    模板输出变量
     * @param  array  $config  模板参数
     * @return mixed
     */
    protected function display($content = '', $vars = [])
    {
        return $this->view->display($content, $vars);
    }

    /**
     * 模板变量赋值
     * @access protected
     * @param  mixed $name  要显示的模板变量
     * @param  mixed $value 变量的值
     * @return $this
     */
    protected function assign($name, $value = '')
    {
        $this->view->assign($name, $value);

        return $this;
    }

    /**
     * 视图过滤
     * @access protected
     * @param  Callable $filter 过滤方法或闭包
     * @return $this
     */
    protected function filter($filter)
    {
        $this->view->filter($filter);

        return $this;
    }

    /**
     * 初始化模板引擎
     * @access protected
     * @param  array|string $engine 引擎参数
     * @return $this
     */
    protected function engine($engine)
    {
        $this->view->engine($engine);

        return $this;
    }

    /**
     * 图片上传
     *
     * @param UploadedFile $file
     * @param string $path
     * @return string
     */
    protected function uploadImage(UploadedFile $file, $path = null){
        $rules = [
            'fileSize' => 1024 * 1024 * 10,
            'fileExt' => 'jpg,png,gif,bmp,webp',
            'fileMime' => 'image/gif,image/png,image/jpeg,image/bmp,image/webp',
        ];
        $messages = [
            'fileSize' => "文件最大支持10M",
            'fileExt' => '支持的文件格式为jpg,png,gif,bmp,webp',
            'fileMime' => '支持的文件格式为jpg,png,gif,bmp,webp',
        ];
        foreach ($rules as $key => $rule){
            try {
                validate()->checkRule($file, [$key => $rule]);
            } catch (\think\exception\ValidateException $e) {
                throw new \think\Exception($messages[$key] ?? '文件验证失败');
            }
        }

        $disk = Filesystem::disk('public');

        return $disk->url($disk->putFile($path ?? 'file', $file, 'md5'));
    }

    /**
     * 图片上传
     *
     * @param $data
     * @return string
     */
    protected function uploadImageData($data){
        $path = '/storage/' . md5(uniqid()) . '.jpg';
        $data = str_replace('data:image/png;base64,', '', $data);
        file_put_contents('../public' . $path, base64_decode($data));
        return $path;
    }

    protected function file(Request $request, $name)
    {
        $has = isset($_FILES[$name]) && 0 == $_FILES[$name]['error'];
        if (!$has){
            return null;
        }

        return $request->file($name);
    }

}
